#include<stdio.h>
#include<stdlib.h>
#include<strings.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
//#include<arpa/inet.h>
#include<linux/in.h>

#define PORT 9200
#define HOST "172.16.14.106"
#define BACKLOG 10

int main(int argc, char *argv[]){
  // int sockfd;
  // struct sockaddr_in my_addr;
  // sockfd = socket(AF_NET, SOCK_STREAM, 0);
  // if(sockfd== -1){
  //   perror("socket");
  //   exit(EXIT_FAILURE)
  // }
  // my_addr.sin_family = AF_NET;
  // my_addr.sin_port = htons(PORT);
  // my_addr.sin_addr.s_addr = inet_addr(HOST);
  int fd_server,fd_client;
  struct sockaddr_in server_addr;
  struct sockaddr_in client_addr;
  int err;
  pid_t pid;
  fd_server = socket(AF_INET, SOCK_STREAM, 0);
  if(fd_server== -1){
    perror("socket");
    exit(1);
  }
  bzero(&server_addr,sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(PORT);
  server_addr.sin_addr.s_addr = INADDR_ANY;
  err = bind(fd_server,(struct sockaddr*)&server_addr,sizeof(server_addr));
  if(err<0){
    printf("bind error\n");
    exit(1);
  }
  err = listen(fd_server,BACKLOG);
  if(err<0){
    printf("listen error\n");
    exit(1);
  }

  for (;;) {
    /* code */
    int addr_len = sizeof(struct sockaddr);
    fd_client = accept(fd_server,(struct sockaddr*)&client_addr, &addr_len);
    if(fd_client<0){
      printf("continue...\n");
      continue;
    }
    show_client_info(&client_addr);
    pid = fork();
    if(pid==0){
      close(fd_server);
      client_handler(fd_client);
    }else{
      close(fd_client);
    }
  }

}

void client_handler(int fd){
  ssize_t size = 0;
  char buffer[1024];
  //for (;;) {
    size = read(fd,buffer,1024);
    if(size == 0){
      return;
    }
    sprintf(buffer, "%d bytes altogether \n",size);
    write(fd, buffer, strlen(buffer));
  //}
}

void show_client_info(struct sockaddr_in client_addr) {
  printf("/nThe IP of client is:%s",inet_ntoa(client_addr.sin_addr));
  printf("/nThe Port of client is:%d/n",ntohs(client_addr.sin_port));
}